<template>
    <div style="display: flex; flex-direction: column;">
        <el-table :data="enterpriseRelations" style="width: 100%; table-layout: fixed;margin-top: 30px;">
            <el-table-column prop="name" label="企业名称" :min-width="200" align="center"
                header-align="center"></el-table-column>

            <el-table-column label="上游企业" :min-width="300" align="center" header-align="center">
                <template #default="{ row }">
                    <div v-if="row.upStream[0].proportionEquity != null">
                        <div v-for="(item, index) in row.upStream" :key="index">
                            {{ item.enterpriseName }}（{{ item.legalPerson }}，{{ item.proportionEquity }}%）
                        </div>
                    </div>
                    <div v-else>暂无关联企业</div>
                </template>
            </el-table-column>

            <el-table-column label="下游企业" :min-width="300" align="center" header-align="center">
                <template #default="{ row }">
                    <div v-if="row.upStream[0].proportionEquity != null">
                        <div v-for="(item, index) in row.downStream" :key="index">
                            {{ item.enterpriseName }}（{{ item.legalPerson }}，{{ item.proportionEquity }}%）
                        </div>
                    </div>
                    <div v-else>暂无关联企业</div>
                </template>
            </el-table-column>

            <el-table-column label="操作" :min-width="200" align="center" header-align="center">
                <template #default="{ row }">
                    
                    <el-button @click="editRelation(row)" size="small" type="warning">编辑关系</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 编辑股权关系弹窗 -->
        <el-dialog v-model="isEditRelationDialogVisible" title="编辑股权关系" width="600px">
            <div v-if="editRelationForm">
                <p><strong>企业名称：</strong>{{ editRelationForm.name }}</p>
                <div
                    style="margin: 20px 0; height: 1px; background: linear-gradient(to right, #409EFF, #eee, #409EFF); opacity: 0.8;">
                </div>
                <p><strong>上游企业：
                    </strong></p>

                <div style="margin-bottom: 10px;">
                    <el-button size="small" type="primary" @click="addUpStream">新增一行</el-button>
                    <el-button size="small" type="danger" @click="removeUpStream">删除一行</el-button>
                </div>

                <el-table :data="editRelationForm.upStream" border style="width: 100%; margin-bottom: 20px;">
                    <el-table-column label="企业名称" align="center">
                        <template #default="{ row }">
                            <el-input v-model="row.enterpriseName" placeholder="请输入企业名称"
                                input-style="text-align: center;" />
                        </template>
                    </el-table-column>

                    <el-table-column label="法人" align="center">
                        <template #default="{ row }">
                            <el-input v-model="row.legalPerson" placeholder="请输入法人" input-style="text-align: center;" />
                        </template>
                    </el-table-column>

                    <el-table-column label="持股比例" align="center">
                        <template #default="{ row }">
                            <el-input v-model.number="row.proportionEquity" placeholder="请输入持股比例" type="number" min="0"
                                max="100" input-style="text-align: center;" />
                        </template>
                    </el-table-column>
                </el-table>
                <div
                    style="margin: 20px 0; height: 1px; background: linear-gradient(to right, #409EFF, #eee, #409EFF); opacity: 0.8;">
                </div>
                <p><strong>下游企业：</strong></p>
                <div style="margin-bottom: 10px;">
                    <el-button size="small" type="primary" @click="addDownStream">新增一行</el-button>
                    <el-button size="small" type="danger" @click="removeDownStream">删除一行</el-button>
                </div>
                <el-table :data="editRelationForm.downStream" border style="width: 100%; margin-bottom: 20px;">
                    <el-table-column label="企业名称" align="center">
                        <template #default="{ row }">
                            <el-input v-model="row.enterpriseName" placeholder="请输入企业名称"
                                input-style="text-align: center;" />
                        </template>
                    </el-table-column>

                    <el-table-column label="法人" align="center">
                        <template #default="{ row }">
                            <el-input v-model="row.legalPerson" placeholder="请输入法人" input-style="text-align: center;" />
                        </template>
                    </el-table-column>

                    <el-table-column label="持股比例" align="center">
                        <template #default="{ row }">
                            <el-input v-model.number="row.proportionEquity" placeholder="请输入持股比例" type="number" min="0"
                                max="100" input-style="text-align: center;" />
                        </template>
                    </el-table-column>
                </el-table>

            </div>

            <template #footer>
                <el-button @click="isEditRelationDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveEditedRelation">保存</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

const enterpriseRelations = ref([]);  // 存储股权关系
const isRelationDetailDialogVisible = ref(false);  // 控制详情弹窗的显示
const isAddRelationDialogVisible = ref(false);  // 控制新增弹窗的显示
const selectedRelation = ref(null);  // 选中的股权关系
const newRelation = ref({
    enterpriseName: '',
    upStream: [],
    downStream: [],
    proportionEquity: ''
});
const isEditRelationDialogVisible = ref(false);
const editRelationForm = ref({
    id: null,
    name: '',
    upStream: [],
    downStream: []
});



const fetchRelations = () => {
    axios.get('http://localhost:3000/admin/relations')
        .then((res) => {
            console.log(JSON.stringify(res))
            if (res.data && res.data.code === 200) {
                // 解析股权关系
                const formattedData = res.data.data.map(relation => {
                    const relationsObj = JSON.parse(relation.relations);
                    const enterpriseId = relation.enterprise_id; // 这里改为使用 relation.enterprise_id

                    if (!enterpriseId) {
                        console.error('企业ID为空，无法获取企业名称');
                        return {
                            id: relation.id,
                            name: '未知企业',
                            enterpriseId:relation.enterprise_id,
                            upStream: relationsObj.upStreamJSON || [],
                            downStream: relationsObj.downStreamJSON || []
                        };
                    }

                    // 根据企业id去获取企业名称
                    return axios.get(`http://localhost:3000/admin/enterprises/${enterpriseId}`)
                        .then((enterpriseRes) => {
                            console.log("企业信息："+JSON.stringify(enterpriseRes));
                            // 返回一个包含企业名称和股权关系的对象
                            return {
                                id: relation.id,
                                name: enterpriseRes.data && enterpriseRes.data.name, // 获取企业名称
                                enterpriseId:relation.enterprise_id,
                                upStream: relationsObj.upStreamJSON || [],
                                downStream: relationsObj.downStreamJSON || []
                            };
                        })
                        .catch((enterpriseErr) => {
                            console.error('获取企业名称失败', enterpriseErr);
                            return {
                                id: relation.id,
                                name: '未知企业', // 如果获取失败，设置为默认值
                                upStream: relationsObj.upStreamJSON || [],
                                downStream: relationsObj.downStreamJSON || []
                            };
                        });
                });

                // 等待所有请求完成后，更新数据
                Promise.all(formattedData).then((result) => {
                    enterpriseRelations.value = result;
                });
            }
        })
        .catch((err) => {
            console.error('获取股权关系失败', err);
            ElMessage.error('获取股权关系失败');
        });
};

// 点击“编辑关系”按钮
const editRelation = (relation) => {
    editRelationForm.value = {
        id: relation.id, // 企业 ID（用于查企业名）
        name: relation.name,
        upStream: JSON.parse(JSON.stringify(relation.upStream)),
        downStream: JSON.parse(JSON.stringify(relation.downStream)),
        enterpriseId: relation.enterpriseId  // 👈 用来提交股权关系主键
    };
    isEditRelationDialogVisible.value = true;
};


// 添加上游企业
const addUpStream = () => {
    editRelationForm.value.upStream.push({
        enterpriseName: '',
        legalPerson: '',
        proportionEquity: null
    });
};
// 添加下游企业
const addDownStream = () => {
    editRelationForm.value.downStream.push({
        enterpriseName: '',
        legalPerson: '',
        proportionEquity: null
    });
};
// 删除上游企业
const removeUpStream = (index) => {
    // 检查是否还有多于一个项，只有在列表中多于一个项时才能删除
    if (editRelationForm.value.upStream.length > 1) {
        // 从后往前删除
        editRelationForm.value.upStream.splice(editRelationForm.value.upStream.length - 1, 1);
    } else {
        ElMessage.warning('至少保留一个上游企业');
    }
};

// 删除下游企业
const removeDownStream = (index) => {
    // 检查是否还有多于一个项，只有在列表中多于一个项时才能删除
    if (editRelationForm.value.downStream.length > 1) {
        // 从后往前删除
        editRelationForm.value.downStream.splice(editRelationForm.value.downStream.length - 1, 1);
    } else {
        ElMessage.warning('至少保留一个下游企业');
    }
};

const saveEditedRelation = () => {
    const updatedRelation = {
        id: editRelationForm.value.id,         // 股权关系记录主键
        enterpriseId: editRelationForm.value.enterpriseId,       // 企业ID
        relations: {
            upStreamJSON: editRelationForm.value.upStream.map(item => ({
                enterpriseName: item.enterpriseName,
                legalPerson: item.legalPerson,
                proportionEquity: item.proportionEquity
            })),
            downStreamJSON: editRelationForm.value.downStream.map(item => ({
                enterpriseName: item.enterpriseName,
                legalPerson: item.legalPerson,
                proportionEquity: item.proportionEquity
            }))
        }
    };

    axios
        .put(`http://localhost:3000/admin/relations`, updatedRelation)
        .then(() => {
            ElMessage.success('股权关系更新成功！');
            isEditRelationDialogVisible.value = false;
            fetchRelations();  // 重新加载股权关系
        })
        .catch((error) => {
            console.error('股权关系更新失败:', error);
            ElMessage.error('股权关系更新失败');
        });
};




const viewRelationDetails = (relation) => {
    selectedRelation.value = relation;
    isRelationDetailDialogVisible.value = true;
};

const addRelation = () => {
    axios.post('/admin/relations', newRelation.value)
        .then(() => {
            ElMessage.success('股权关系新增成功！');
            isAddRelationDialogVisible.value = false;
            fetchRelations();  // 重新加载股权关系
        })
        .catch((error) => {
            console.error('股权关系新增失败:', error);
            ElMessage.error('股权关系新增失败');
        });
};

const deleteRelation = (relation) => {
    axios.delete(`/admin/relations/${relation.id}`)
        .then(() => {
            fetchRelations();  // 重新加载股权关系
            ElMessage.success('股权关系删除成功！');
        })
        .catch((err) => {
            console.error('删除失败', err);
            ElMessage.error('删除失败');
        });
};

const openAddRelationDialog = () => {
    isAddRelationDialogVisible.value = true;
};

onMounted(fetchRelations);  // 组件加载时获取股权关系
</script>


<style scoped>
h3 {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 20px;
}

.el-button {
    margin-right: 10px;
}
</style>